export function generateNginxConfig(data, path) {
    let config = `
# 全局配置
pid ${path}/logs/nginx.pid;
error_log ${path}/logs/error.log;

# 工作进程配置
worker_processes auto;
# 事件模块配置
events {
    worker_connections 1024;
}

# HTTP 模块配置
http {
    # 日志配置
    access_log ${path}/logs/access.log;

    include       mime.types;
    default_type  application/octet-stream;

    #配置临时文件路径
    client_body_temp_path ${path}/temp/client_body_temp;
    proxy_temp_path ${path}/temp/proxy_temp;
    fastcgi_temp_path ${path}/temp/fastcgi_temp;
    uwsgi_temp_path ${path}/temp/uwsgi_temp;
    scgi_temp_path ${path}/temp/scgi_temp;

    # 其他HTTP相关配置
    sendfile        on;
    keepalive_timeout  65;
    
    # 增加对大文件的支持
    client_max_body_size 20M;
    
    # 解决跨域问题
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
    
    # 开启gzip压缩
    gzip on;
    gzip_min_length 1k;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml;
    gzip_vary on;
`;

    data.forEach((project, projectIndex) => {
        config += `
    server {
        listen ${project.port};
        server_name localhost;
        
        # 设置根目录访问权限
        location / {
            root ${project.projectPath};
            index index.html index.htm;
            # 解决单页应用刷新404问题
            try_files $uri $uri/ /index.html;
            # 增加目录列表功能
            autoindex on;
            # 允许访问
            allow all;
        }
`;

        project.servers.forEach((server, serverIndex) => {
            // 添加默认的路径参数 - 使用 /api 或 /api1, /api2 等
            const pathParam = server.path || `/api${project.servers.length > 1 ? serverIndex + 1 : ''}`;
            
            config += `
        location ${pathParam} {
            proxy_pass ${server.api};
            proxy_http_version 1.1;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_connect_timeout 60s;
            proxy_read_timeout 60s;
            proxy_send_timeout 60s;
        }
`;
        });

        config += `
        # 静态资源处理
        location ~* \\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
            root ${project.projectPath};
            expires max;
            add_header Cache-Control "public, max-age=31536000";
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
`;
    });

    config += `}`;
    return config;
}